#include "Window.h"

Game* Window::_game				= new Game();
unsigned Window::_frameInterval = 25; //msec. 40 fps

Window::Window(unsigned width, unsigned height, const char* name) 
: _width(width)
, _height(height)
, _name(name)
{}

bool Window::Initialize(int argc, char** argv)
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
	glutInitWindowPosition(100, 100);
	glutInitWindowSize(_width, _height);

	_mainWindow = glutCreateWindow(_name);

	if (_mainWindow != 0)
	{
		glutSetWindow(_mainWindow);
		_BindHandlers();
	}

	return (_mainWindow != 0);
}

void Window::_BindHandlers()
{
	glutDisplayFunc(_DisplayHandler);
	glutKeyboardFunc(_KeyboardHandlerASCII);
	glutSpecialFunc(_KeyboardSpecialHandler);
	glutReshapeFunc(_ReshapeHandler);
	glutTimerFunc(_frameInterval  , _RedrawHandler, 0);
	glutTimerFunc(Game::Interval(), _UpdateHandler, 0);
}

#pragma warning(disable:4100) // actually useless formal parameter resulted by GLUT API

void Window::_UpdateHandler(int value)
{
	_game->Update();
	glutTimerFunc(Game::Interval(), _UpdateHandler, 0);
}

void Window::_RedrawHandler(int value)
{
	glutPostRedisplay();
	glutTimerFunc(_frameInterval, _RedrawHandler, 0);
}

#pragma warning(default:4100)

void Window::_KeyboardSpecialHandler(int key, int x, int y)
{
	_game->KeyPressed(key, 0, x, y);
}

void Window::_KeyboardHandlerASCII(unsigned char key, int x, int y)
{
	_game->KeyPressed(0, key, x, y);
}

void Window::_ReshapeHandler(int width, int height)
{
	glViewport(0, 0, (GLsizei)width, (GLsizei)height);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(0.0, (GLdouble)width, 0.0, (GLdouble)height);
}

void Window::BeginLoop()
{
	glutMainLoop();
}

void Window::_DisplayHandler()
{
	_game->Draw();
}

unsigned Window::width()
{
    return _width;
}

unsigned Window::height()
{
    return _height;
}